package com.mingke.java.NIO;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author mingke
 * @function TODO
 * @date 2021/11/8
 */
public class NIOSocketHandler extends Thread{
    //处理器持有一个客户端对象
    private NIOSocketClient socketClient;

    //自定义的处理函数
    public NIOSocketHandler(SocketChannel channel, ByteBuffer byteBuffer) throws IOException {
        socketClient = new NIOSocketClient(channel, byteBuffer);
        //设置客户端全局统一的ID
        socketClient.setCid(NIOSocketServer.cidNum++);

    }

    @Override
    public void run() {
        super.run();
        //设置为读入模式
        socketClient.getByteBuffer().flip();
        //获取到当前的长度
        int bufferLength = socketClient.getByteBuffer().limit();
        //设置缓冲数组
        byte bytes[] = new byte[bufferLength];
        //读入数据到缓冲数组
        socketClient.getByteBuffer().get(bytes, 0, bufferLength);
        System.out.println("数据长度为："+bufferLength+" 数据内容如下");
        for(int i = 0; i < bufferLength; i++) {
            if(i == bufferLength-1) {
                System.out.print(bytes[i] + "\n");
            }else {
                System.out.print(bytes[i] + " ");
            }
        }
        //清除残余无用数据
        socketClient.getByteBuffer().clear();
    }
}
